package org.tuestudent.grouppa;

import org.tuestudent.grouppa.AppContext.OnJoinedGroupsChangeListener;
import org.tuestudent.grouppa.GroupViewController.JoinGroupResponse;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MyGroups extends Fragment implements OnItemClickListener,
        OnJoinedGroupsChangeListener {

    private String[] groupItems;

    private ListView groupList;
    private GrouppaScreen grouppaScreen;
    private static MyGroups instance = null;

    public static MyGroups getInstance() {
        return instance;
    }

    /**
     * this method is called on when a group (in which the user is enrolled) is
     * selected and redirects the user to the group info screen of the
     * corresponding group.
     * 
     * @param ID
     *            the string that specifies the group ID
     * @pre {@code ID != null}
     * @post the user is at the group info screen of the group corresponding to
     *       {@code ID}
     */
    private void openGroup(String ID) {
        // TODO:create code to open the group with the corresponding ID
    }

    /**
     * this method creates a popup to join a new group
     * 
     * @pre true
     * @post the joinGroupPopup is opened
     */
    private void joinGroupPopup() {
        // make the popup visible
        final AlertDialog joinGroupPopup =
                grouppaScreen.showPopUp(R.layout.popup_join_group);
        // add a listener to the button of the popup so it can do something when
        // pressed on
        final Button joinGroup =
                (Button) joinGroupPopup.findViewById(R.id.create_group);
        joinGroup.setOnClickListener(new OnClickListener() {

            // declare what to do when the button is pressed
            @Override
            public void onClick(View arg0) {
                // get the user input
                String groupName =
                        ((EditText) joinGroupPopup.findViewById(R.id.groupname))
                                .getText().toString();
                String groupPin =
                        ((EditText) joinGroupPopup.findViewById(R.id.password1))
                                .getText().toString();
                boolean check = true;
                // check if the group name is of the proper form
                if ( !isValid(groupName)) {
                    check = false;
                    ((EditText) joinGroupPopup.findViewById(R.id.groupname))
                            .setError("groupname may only contain (a-z, A-Z, 0-9)");
                }
                // check if the pin field is not empty
                if (groupPin.isEmpty()) {
                    ((EditText) joinGroupPopup.findViewById(R.id.password1))
                            .setError("Please choose a pincode");
                    check = false;
                }
                // check if the pin field contains 4 digits
                if (groupPin.length() < 4) {
                    ((EditText) joinGroupPopup.findViewById(R.id.password1))
                            .setError("Pincode should contain 4 digits");
                    check = false;
                }
                if (check) {
                    joinGroupPopup.dismiss();
                    joinGroup(groupName, groupPin);
                }
            }
        });
        
//      Selecting the ImageButton to cancel the creation of a group
        final ImageButton cancel = (ImageButton) joinGroupPopup.findViewById(R.id.cancelButton);
        cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                joinGroupPopup.dismiss();
            }
        });
    }

    /**
     * add the user to the group if groupName and groupPassword match
     * 
     * @param groupName
     *            the name of the group
     * @param groupPassword
     *            the password of the group
     */
    private void joinGroup(String groupName, String groupPassword) {
        // CHECK: show popup to wait for completion
        grouppaScreen.busyMessage("joining group...");
        // CHECK: send request to create a group
        GroupViewController.getInstance().joinGroup(groupName, groupPassword);

    }

    /**
     * this method creates a popup to create a new group
     * 
     * @pre true
     * @post the createGroupPopup is opened
     */
    private void createGroupPopup() {

        // final createGroupPopup createGroupPopup = new createGroupPopup();
        // make the popup visible
        // createGroupPopup.show(getFragmentManager(), "createGroup");
        final AlertDialog createGroupPopup =
                grouppaScreen.showPopUp(R.layout.popup_create_group);
        // add a listener to the button of the popup so it can do something when
        // pressed on
        final Button createGroup =
                (Button) createGroupPopup.findViewById(R.id.create_group);
        createGroup.setOnClickListener(new OnClickListener() {

            // declare what to do when the button is pressed
            @Override
            public void onClick(View arg0) {
                // get the user input
                String groupName =
                        ((EditText) createGroupPopup
                                .findViewById(R.id.groupname)).getText()
                                .toString();
                String groupPin =
                        ((EditText) createGroupPopup
                                .findViewById(R.id.createPin)).getText()
                                .toString();
                String groupPin2 =
                        ((EditText) createGroupPopup
                                .findViewById(R.id.confirmPin)).getText()
                                .toString();
                boolean check = true;
                // check if the group name is of the proper form
                if ( !isValid(groupName)) {
                    check = false;
                    ((EditText) createGroupPopup.findViewById(R.id.groupname))
                            .setError("groupname may only contain (a-z, A-Z, 0-9)");
                }
                // check if the pin field is not empty
                if (groupPin.isEmpty()) {
                    ((EditText) createGroupPopup.findViewById(R.id.createPin))
                            .setError("Please choose a pincode");
                    check = false;
                }
                // check if the pin field contains 4 digits
                if (groupPin.length() < 4) {
                    ((EditText) createGroupPopup.findViewById(R.id.createPin))
                            .setError("Pincode should contain 4 digits");
                    check = false;
                }
                // check if the verification pin matches the other pin
                if ( !groupPin.equals(groupPin2)) {
                    ((EditText) createGroupPopup.findViewById(R.id.confirmPin))
                            .setError("this does not match the pincode above");
                    check = false;
                }
                if (check) {
                    createGroupPopup.dismiss();
                    createGroup(groupName, groupPin);
                }
            }
        });
        // TODO:create close button
        
        ImageButton cancel = (ImageButton) createGroupPopup.findViewById(R.id.cancelButton);
        cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                createGroupPopup.dismiss();
            }
        });
    }

    /**
     * creates a new group with id groupName and password groupPassword
     * 
     * @param groupName
     *            the name of the group
     * @param groupPassword
     *            the password of the group
     */
    private void createGroup(String groupName, String groupPassword) {
        // CHECK: show popup to wait for completion
        grouppaScreen.busyMessage("creating group...");
        // CHECK: send request to create a group
        GroupViewController.getInstance().createGroup(groupName, groupPassword);
    }

    /**
     * popup to confirm that the group has been created
     * 
     * @param groupName
     *            the name of the created group
     */
    private void groupCreatedPopup(String groupName) {
        // TODO:create popup to confirm that group groupName has been created
        // TODO:create 'OK' button to confirm and close the popup
    }


    // method to check if a nickname contains only (capital) letters and numbers, with spaces
    public boolean isValid(String name) {
        return name.matches("[a-zA-Z0-9 ]+");
    }

    // When the Fragment is attached to the activity
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.grouppaScreen = (GrouppaScreen) activity;
    }

    ArrayAdapter<String> groupListAdapter;

    // ----------------onCreateView for the MyGroup Fragment-------------------
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Inflate the view to its container
        View myGroups =
                inflater.inflate(R.layout.fragment_my_groups, container, false);

        // Select the ListView to populate with the array
        groupList = (ListView) myGroups.findViewById(R.id.listview_groups);

        // Sets the list of groups to the ListView in the My Groups fragment
        groupListAdapter =
                new ArrayAdapter<String>(grouppaScreen,
                        R.layout.group_list_item, Main.getContext().getJoinedGroupsArray());
        groupList.setAdapter(groupListAdapter);

        // Set onItemSelectListener to the ListViewItems
        groupList.setOnItemClickListener(this);

        Button joinButton =
                (Button) myGroups.findViewById(R.id.button_joingroup);
        joinButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                joinGroupClick(arg0);
            }
        });
        Button createButton =
                (Button) myGroups.findViewById(R.id.button_creategroup);
        createButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                createGroupClick(arg0);
            }
        });

        return myGroups;
    }

    /**
     * Called when user touches a group
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        String groupname = (String) groupList.getItemAtPosition(position);
        activateGroup(groupname);
        grouppaScreen.selectFragment(1);
    }

    private void activateGroup(String groupname) {
        // CHECK: make groupname the active group for this user
        try {
            GroupViewController.getInstance().makeActiveGroup(groupname);
        } catch (Exception e) {
            Main.getContext().grouppaActivity
                    .errorPopup("Error:Tried to switch to non existent group");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        AppContext ctx = Main.getContext();
        ctx.setCurrentViewController(GroupViewController.getInstance());
        ctx.setOnJoinedGroupsChangeListener(this);
        instance = this;
        Main.getContext().currentGrouppaFragment = this;
    }

    @Override
    public void onJoinedGroupsChange(String[] newGroups) {
        groupListAdapter =
                new ArrayAdapter<String>(grouppaScreen,
                        R.layout.group_list_item, newGroups);
        groupList.setAdapter(groupListAdapter);
    }

    public void createGroupClick(View button) {
        createGroupPopup();
    }

    public void joinGroupClick(View button) {
        joinGroupPopup();
    }

    public void onJoinGroupResponse(JoinGroupResponse response) {
        if ( !response.joined) {
            grouppaScreen.errorPopup(response.errorReason);
        } else {
            grouppaScreen.actionSuccess("Group joined!");
        }

    }
}
